﻿using Furion.FriendlyException;
using Gear.Core.ErrorControl;
using Gear.ORM.Core.DeepDB;
using Gear.ORM.Core.Tenant;
using Gear.ToolKits.Helper;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Gear.Web.Api.DynamicDataApi.Macro
{
    /// <summary>
    /// 查询转换正则宏
    /// </summary>
    public class ConvertRegexMacro
    {

        #region == 验证规则 ==
        public static System.Text.RegularExpressions.Regex[] reqRegex = new System.Text.RegularExpressions.Regex[]
        {
            new System.Text.RegularExpressions.Regex(@"(\~.+\~)",RegexOptions.IgnoreCase),
        };
        #endregion

        /// <summary>
        /// Select匹配
        /// </summary>
        /// <param name="_content"></param>
        /// <param name="param"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string SelectTrans(string _content, Dictionary<string, object> param)
        { 
            if (string.IsNullOrEmpty(_content)) throw Oops.Oh(ErrorCodeModel.E2100_2, "");
            if (_content.StartsWith("sql:", StringComparison.CurrentCultureIgnoreCase))
            {
                if (param != null)
                {

                    foreach (var reg in reqRegex)
                    {
                        var match = reg.Match(_content);
                        while (match.Success)
                        {
                            param.TryGetValue(match.Value.Replace("~", null), out object varVal);

                            _content = _content.Replace(match.Value, varVal.ToString());
                            _content = _content.Replace("sql:", null);
                            match = reg.Match(_content);
                        }
                    }

                }
            }
            return _content;
        }

        /// <summary>
        /// 宏匹配
        /// </summary>
        /// <param name="_content"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public static object MacroTrans(string _content, string code)
        {
            object res = null;
            switch(_content)
            {
                case "sysdate()":
                    res = TimeTrans(_content, code);
                    break;
                case "sysuserid()":
                    res = LoginUserIdTrans(_content);
                    break;
                case "sysuserpack()":
                    res = UserPackTrans(_content);
                    break;
                case "sysorgid()":
                    res = LoginOrgIdTrans(_content);
                    break;
                case "sysorgpack()":
                    res = OrgPackTrans(_content);
                    break;
                case "systenantid()":
                    res = TenantIdTrans(_content);
                    break;
                case "systenantpack()":
                    res = TenantPackTrans(_content);
                    break;
            }
            return res;
        }

        #region == 宏匹配规则 ==
        /// <summary>
        /// Time匹配
        /// </summary>
        /// <param name="_content"></param>
        /// <returns></returns>
        public static string TimeTrans(string _content,string code)
        {
            if (string.IsNullOrEmpty(_content)) return "";
            using (var pool = DeepPool.DeepSugar())
            {
                var time = pool.Ado.SqlQuery<DateTime>(@"select now() from dual").SingleOrDefault();
                _content = time.ToString(code);
                pool.Close();
            }

            return _content;
        }

        /// <summary>
        /// LoginUserId匹配
        /// </summary>
        /// <param name="_content"></param>
        /// <returns></returns>
        public static string LoginUserIdTrans(string _content)
        {
            return _content;
        }

        /// <summary>
        /// UserPack匹配
        /// </summary>
        /// <param name="_content"></param>
        /// <returns></returns>
        public static string UserPackTrans(string _content)
        {
            return _content;
        }

        /// <summary>
        /// LoginOrgId匹配
        /// </summary>
        /// <param name="_content"></param>
        /// <returns></returns>
        public static string LoginOrgIdTrans(string _content)
        {
            return _content;
        }

        /// <summary>
        /// OrgPack匹配
        /// </summary>
        /// <param name="_content"></param>
        /// <returns></returns>
        public static string OrgPackTrans(string _content)
        {
            return _content;
        }

        /// <summary>
        /// TenantId匹配
        /// </summary>
        /// <param name="_content"></param>
        /// <returns></returns>
        public static string TenantIdTrans(string _content)
        {
            if (string.IsNullOrEmpty(_content)) return "";
            _content = MemoryCacheHelper.Get<string>("tenantid");

            if (string.IsNullOrEmpty(_content))
            {
                HttpContextAccessor context = new HttpContextAccessor();
                var local = context.HttpContext?.Connection.LocalIpAddress.MapToIPv4().ToString() + ":" + context.HttpContext?.Connection.LocalPort.ToString();
                // 根据local获取当前租户
                using (var pool = DeepPool.DeepSugar())
                {
                    _content = pool.Queryable<Tenants>().First(it => it.Host == local)?.TenantId;
                    pool.Close();
                }

            }

            return _content;
        }

        /// <summary>
        /// TenantPack匹配
        /// </summary>
        /// <param name="_content"></param>
        /// <returns></returns>
        public static string TenantPackTrans(string _content)
        {
            return _content;
        }
        #endregion
    }
}
